/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.ius.datasource
 */
package com.apache.database.datasource;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.model.MethodParam;
import com.apache.tools.StrUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * description:  
 * @author qihan 创建时间：2017-9-18  
 */
public class DataSourceAspect {
	public void before(JoinPoint point) {
		String className = point.getTarget().getClass().getName();
		try {
			String key = "";
			Object[] obj = point.getArgs();
			if(null ==obj || obj.length<=0 || "com.apache.ius.impl.IusPubDaoImpl".equals(className)) {
				return;
			}
			if(DynamicDataSource.getInstance().getEnableIncludeRpc() && className.indexOf("com.apache.rpc") !=-1){
				key = DynamicDataSource.getInstance().getRpcDb().getSysEname();
				if (obj[0] instanceof ParamsVo) {
					ParamsVo vo = (ParamsVo) obj[0];
					vo.setParams("datasource",key);
				}else if(obj[0] instanceof MethodParam){
					MethodParam param = (MethodParam)obj[0];
					param.setParams("datasource",key);
				}
			}else{
				if (obj[0] instanceof ParamsVo) {
					ParamsVo vo = (ParamsVo) obj[0];
					key = String.valueOf(vo.getParams("datasource"));
				} else if(obj[0] instanceof MethodParam){
					MethodParam param = (MethodParam)obj[0];
					key = String.valueOf(param.getParamsByKey("datasource"));
				}
				key = StrUtil.doNull(key, "default");
			}
			if(!"default".equals(key) && !DynamicDataSource.getInstance().checkDataSource(key)){
				DynamicDataSource.getInstance().addDataSource(key);//动态添加数据源
			}
			DynamicDataSourceHolder.putDataSource(key);
		} catch (Exception e) {
		}
	}
}
